﻿#if NET7_0_OR_GREATER
using System;
using System.Collections.Generic;
using System.Text;

using zijian666.Abstractions;
using zijian666.Convertor.Base;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Convertor.Extra;
/// <summary>
/// <seealso cref="IParsable{T}"/> 转换器
/// </summary>
/// <typeparam name="T"></typeparam>
public class IParsableConvertor<T> : IConvertor<T>
    where T : IParsable<T>
{
    public virtual uint Priority => 1;

    protected string _typeFriendlyName = typeof(T).GetFriendlyName();

    /// <inheritdoc />
    public virtual ConvertResult<T> Convert(IConvertContext context, object? input)
    {
        if (input is string s && T.TryParse(s, context.Settings.GetToStringArgument(typeof(T))?.FormatProvider, out var result))
        {
            return new(result);
        }
        return ExceptionHelper.ConvertFail(input, _typeFriendlyName, context.Settings.CultureInfo, null);
    }
}

/// <summary>
/// <seealso cref="ISpanParsable{T}"/> 转换器
/// </summary>
/// <typeparam name="T"></typeparam>
public class ISpanParsableConvertor<T> : IParsableConvertor<T>
    where T : ISpanParsable<T>
{
    public override uint Priority => base.Priority + 1;
    /// <inheritdoc />
    public override ConvertResult<T> Convert(IConvertContext context, object? input)
    {
        if (input is string s && T.TryParse(s.AsSpan(), context.Settings.GetToStringArgument(typeof(T))?.FormatProvider, out var result))
        {
            return new(result);
        }
        return ExceptionHelper.ConvertFail(input, _typeFriendlyName, context.Settings.CultureInfo, null);
    }
}

#endif